package com.panda.file.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.panda.file.service.FileService;
import com.panda.utils.CommonUtils;

@Controller
public class FileController {

	@Resource
	private FileService fileService;

	@RequestMapping("/upload/file")
	@ResponseBody
	public String upload(MultipartFile file, HttpServletRequest request) {
		Long id = -1L;
		try {
			String fileName = file.getOriginalFilename();
			String Suffix=fileName.substring(fileName.lastIndexOf("."));
			String uploadFile = uploadFile(file, request,Suffix);
			com.panda.file.entity.File files=new com.panda.file.entity.File();
			files.setUrl(uploadFile);
			files.setName(fileName);
			fileService.save(files);
			id=files.getId();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return CommonUtils.msgCallback(true, "上传成功", null, JSON.toJSONString(id));
	}
	
	@RequestMapping("/upload/image")
	@ResponseBody
	public String image(MultipartFile file, HttpServletRequest request) {
		String uploadFile ="";
		try {
			String fileName = file.getOriginalFilename();
			String Suffix=fileName.substring(fileName.lastIndexOf("."));
			uploadFile = uploadFile(file, request,Suffix);
			com.panda.file.entity.File files=new com.panda.file.entity.File();
			files.setUrl(uploadFile);
			files.setName(fileName);
			fileService.save(files);
			files.getId();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return CommonUtils.msgCallback(true, "上传成功", null, JSON.toJSONString(uploadFile));
	}

	// 文件上传
	public String uploadFile(MultipartFile file, HttpServletRequest request,String Suffix) throws IOException {
		String path = request.getSession().getServletContext().getRealPath("file/");
		File tempFile = new File(path, new Date().getTime() + Suffix);
		if (!tempFile.getParentFile().exists()) {
			tempFile.getParentFile().mkdir();
		}
		if (!tempFile.exists()) {
			tempFile.createNewFile();
		}
		file.transferTo(tempFile);
		return "file/" + tempFile.getName();
	}
}
